//
//  BasePageController.swift
//  DYSwiftFramework
//
//  Created by huangdeyu on 2021/10/21.
//  Copyright © 2021 none. All rights reserved.
//

import UIKit



protocol SubPageProtocol where Self : UIViewController {
    var visiable :Bool{ get set}
}

private class PageControllerFlowLayout : UICollectionViewFlowLayout{
    
    var initialIndex = 0;
    
    override func prepare() {
        super.prepare()
        collectionView?.contentOffset = CGPoint.init(x:  initialIndex.cgFloat * SCREEN_W, y: 0)
    }
}


private class PageCell:UICollectionViewCell {
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    private weak var pageView:UIView?
    func loadPage(view:UIView)  {
        if let v = pageView {
            v.removeFromSuperview()
        }
        pageView = view
        self.contentView.addSubview(view)
        view.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
    }
}

class BasePageController: UIViewController,UICollectionViewDelegateFlowLayout,UICollectionViewDataSource {

    private var collectionView:UICollectionView?
    var viewControllers:[UIViewController] = [] {
        didSet {
            collectionView?.reloadData()
        }
    }
    var currentIndex = 0
    

    override func viewDidLoad() {
        super.viewDidLoad()
        setupContent()
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return viewControllers.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
        let currentVC = viewControllers[indexPath.row]
        if !self.childViewControllers.contains(currentVC) {
            self.addChildViewController(currentVC)
        }
        if let currentCell = cell as? PageCell {
            currentCell.loadPage(view: currentVC.view)
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
        if let view = cell.contentView.subviews.first {
            view.removeFromSuperview()
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return self.view.frame.size
    }
    
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        if !decelerate {
            pageChanged()
        }
    }
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        pageChanged()
    }
    func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
        pageChanged()
    }
    
    private func pageChanged() {
        let offsetX = self.collectionView?.contentOffset.x ?? 0
        let screenW = SCREEN_W
        let index = (offsetX / screenW).int
        if self.currentIndex == index {
            return
        }
        if let vc = viewControllers[self.currentIndex] as? SubPageProtocol {
            vc.visiable = false
        }
        self.currentIndex = index
        onPageChanged(index: index)
        if let vc = viewControllers[index] as? SubPageProtocol {
            vc.visiable = true
        }
    }
    
    private func setupContent() {
        let layout = PageControllerFlowLayout.init()
        layout.scrollDirection = .horizontal
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        layout.initialIndex = 0
        collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
        collectionView?.delegate = self
        collectionView?.dataSource = self
        collectionView?.showsHorizontalScrollIndicator = false
        collectionView?.isPagingEnabled = true
        collectionView?.bounces = false
        collectionView?.register(PageCell.self, forCellWithReuseIdentifier: "cell")
        view.addSubview(collectionView!)
        collectionView?.snp.makeConstraints({ (make) in
            make.edges.equalToSuperview()
        })
    }
    
    func setup(controllers:[UIViewController],visibleIndex:Int) {
        viewControllers = controllers
        ( collectionView?.collectionViewLayout as? PageControllerFlowLayout)?.initialIndex = visibleIndex
        self.currentIndex = visibleIndex
    }
    
    func scrollTo(index:Int,animated:Bool) {
        self.collectionView?.scrollToItem(at: IndexPath.init(row: index, section: 0), at: .left, animated: animated)
        if !animated {
            pageChanged()
        }
    }

    func onPageChanged(index:Int)  {
        debugPrint("切换页面至：\(index)")
    }
}
